﻿namespace NTLib.Core.Manipulators
{
    using NTLib.Core.Args;
    using NTLib.Core.Exceptions;
    using NTLib.Core.Memory;
    using NTLib.Core.Threading;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// base Sealed class that implement the insterface ISealed
    /// </summary>
    /// <typeparam name="Locker">The type of the ocker.</typeparam>
    [DataContract]
    public abstract class SealedBase<Locker> : Disposable, ISealed
        where Locker : ILocker, new()
    {
        #region Fields

        private readonly Locker _locker;
        private bool _isSealed;

        #endregion

        #region Ctor

        /// <summary>
        /// Initializes a new instance of the <see cref="SealedBase{Locker}"/> class.
        /// </summary>
        /// <param name="locker">The locker instance.</param>
        protected SealedBase(Locker locker)
        {
            if (locker == null)
                this._locker = new Locker();
            else
                this._locker = locker;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SealedBase{Locker}"/> class.
        /// </summary>
        protected SealedBase()
        {
            this._locker = new Locker();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a value indicating whether this instance is sealed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is sealed; otherwise, <c>false</c>.
        /// </value>
        [IgnoreDataMember]
        public bool IsSealed
        {
            get
            {
                base.CheckDisposed();
                using (this._locker.ScopeLock(true))
                {
                    return this._isSealed;
                }
            }
        }

        /// <summary>
        /// Gets the locker.
        /// </summary>
        [IgnoreDataMember]
        protected Locker LockerImpl
        {
            get
            {
                base.CheckDisposed();
                return this._locker;
            }
        }

        #endregion

        #region Event

        /// <summary>
        /// Occurs when the sealed status changed.
        /// </summary>
        public event EventHandler<ValueChangedEventArgs<bool>> SealedChanged;

        #endregion

        #region Methods

        /// <summary>
        /// Sealeds this instance.
        /// </summary>
        public void Sealed(CancellationToken token = default(CancellationToken))
        {
            base.CheckDisposed();
            bool changed = false;
            using (this._locker.ScopeLock())
            {
                if (!this._isSealed)
                {
                    this._isSealed = true;
                    changed = true;
                }
            }

            if (changed)
                OnSealedChanged();
        }

        /// <summary>
        /// Checks if the instance is sealed and raise an exception if it is.
        /// </summary>
        /// <param name="msgIfSealed">The MSG if sealed.</param>
        /// <exception cref="NTLib.Core.Exceptions.InstanceSealedException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        protected void CheckSealed(string msgIfSealed = null)
        {
            base.CheckDisposed();
            using (this._locker.ScopeLock(true))
            {
                if (this._isSealed)
                    throw new InstanceSealedException(msgIfSealed);
            }
        }

        /// <summary>
        /// Release the sealed.
        /// </summary>
        protected void UnSealed()
        {
            base.CheckDisposed();
            bool changed = false;
            using (this._locker.ScopeLock())
            {
                if (this._isSealed)
                {
                    this._isSealed = false;
                    changed = true;
                }
            }

            if (changed)
                OnSealedChanged();
        }

        /// <summary>
        /// Called when the sealed status changed.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void OnSealedChanged()
        {
            if (this.SealedChanged != null)
                this.SealedChanged(this, new ValueChangedEventArgs<bool>(!this._isSealed, this._isSealed));
        }

        /// <summary>
        /// Dispose methods called whenever is the dipose origin.
        /// </summary>
        protected override void DisposeEveryTime()
        {
            base.DisposeEveryTime();
            if (this._locker != null && !this._locker.IsDisposed)
                this._locker.Dispose();
        }

        #endregion
    }

    /// <summary>
    /// base Sealed class that inmplement the insterface ISealed
    /// </summary>
    public abstract class SealedBase : SealedBase<NoLocker>
    {
    }
}
